import ImgUpload from '@/components/ImgUpload';
import { ProFormDateTimeRangePicker, ProFormDigit, ProFormRadio } from '@ant-design/pro-components';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import { history, useLocation } from 'umi';
import {Button, Card, Form, message, Space, UploadFile} from 'antd';
import locale from 'antd/es/date-picker/locale/zh_CN';
import { useForm } from 'antd/es/form/Form';
import { Resizable } from 're-resizable';

import { createWindow, getById, updateWindow } from '@/services/window';
import 'moment/locale/zh-cn'

import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import {CheckOutlined, UndoOutlined} from "@ant-design/icons";
// import './index.less';
const Index: React.FC = (props) => {
  const [form] = useForm();
  const divRef = useRef(null);
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [size, setSize] = useState({ width: 100, height: 100 });
  const [imgWidth, setImgWidth] = useState<number>(100);
  const [imgHeight, setImgHeight] = useState<number>(100);
  const location = useLocation();
  const [editObj, setEditObj] = useState({});
  const [imgSrc, setImgSrc] = useState<string>('');
  const formLayout = {
    labelCol: {
      span: 8,
    },
    wrapperCol: {
      span: 12,
    },
  };
  useEffect(() => {
    if (location.state && typeof location.state != 'undefined') {
      const obj = location.state?.formValues;
      setEditObj(obj);
      getById({ id: obj.id }).then((res) => {
        let list = [];
        setSize({ width: res.data.width, height: res.data.height });
        if (res.data.playStart != null) {
          res.data.dataDate = [
            moment(res.data.playStart),
            !!res.data.playEnd ? moment(res.data.playEnd) : null,
          ];
        }

        const element = res.data.file;
        if (!!element) {
          list.push({
            uid: element.id,
            size: element.wjdx,
            name: element.wjmc + '.' + element.wjgs,
            fileName: element.wjmc + '.' + element.wjgs,
            url: element.httpurl,
            percent: 100,
            response: { data: [element] },
          });
          res.data.uploadImgs = list;
        }
        setFileList(list);

        form.setFieldsValue(res.data);
      });
    }else{
      form.setFieldValue('speed',30)
      form.setFieldValue('x',10)
      form.setFieldValue('y',10)
    }
  }, []);

  const onSubmit = async (values: any) => {
    if (values.dataDate != null && values.dataDate != undefined) {
      values.playStart = moment(values.dataDate[0]).format('YYYY-MM-DD HH:mm:ss');
      values.playEnd = !!values.dataDate[1]
        ? moment(values.dataDate[1]).format('YYYY-MM-DD HH:mm:ss')
        : null;
    }
    values.height = size.height || 200;
    values.width = size.width || 200;
    //对联
    values.type = 'bay';
    let file;
    if (fileList.length > 0) {
      for (let i = 0; i < fileList.length; i++) {
        const element = fileList[i].response.data[0];
        if (element.id) {
          file = element;
        } else {
          file = {
            id: element.fileId,
            kind: 'pic',
            localurl: element.url,
            origin: 'window',
            pxh: 10,
            wjdx: element.fileSize,
            wjgs: element.fileType,
            wjmc: element.fileName,
          };
        }
      }
    }
    values.file = file;
    let res;
    if (editObj?.id) {
      values.id = editObj.id;
      res = await updateWindow(values);
    } else {
      res = await createWindow(values);
    }
    if (res.code == '0') {
      message.success('发布成功！');
      history.push('/windowSetting/windowManage');
    }
  };

  useEffect(() => {
    if (fileList.length > 0 && fileList[0].response) {
      setImgSrc(fileList[0].response.data[0].path || fileList[0].response.data[0].httpurl);
    } else {
      setImgSrc('');
    }
  }, [fileList]);
  return (
    <PageContainer
      header={{
        title: false,
      }}
      className="buildFloat"
    >
      <Card title="发布漂浮专栏">
        <ProForm
          form={form}
          layout="horizontal"
          {...formLayout}
          onFinish={onSubmit}
          initialValues={{
            display: '0',
            stat: 'active',
          }}
          submitter={{
            render: (_, dom) => (
              <div style={{ display: 'flex', justifyContent: 'center' }}>
                <Space>
                  {/*{dom}*/}
                  {<Button onClick={() => {
                    _.reset()
                  }}><UndoOutlined />重置</Button>}
                  {<Button type={"primary"} onClick={() => {
                    _.submit()
                  }}><CheckOutlined />提交</Button>}

                </Space>
              </div>
            ),
          }}
        >
          <ProFormText
            rules={[
              {
                required: false,
                message: '专栏描述必填！',
              },
            ]}
            width="md"
            name="des"
            placeholder="请输入专栏描述"
            label="专栏描述"
          />
          <ProFormText width="md" name="link" placeholder="请输入专栏链接" label="专栏链接" />
          <ProFormDigit width="xs" name="x" label="x轴坐标" min={1} />
          <ProFormDigit width="xs" name="y" label="y轴坐标" min={1} />
          <ProFormDigit width="xs" name="speed" label="移动速度" min={1} />
          <ProFormDateTimeRangePicker
            name="dataDate"
            fieldProps={{
              allowEmpty: [false, true],
            }}
            rules={[
              {
                required: false,
                message: '专栏排期必填！',
              },
            ]}
            label="专栏排期"
            locale={locale}
          />
          <ProFormDigit width="xs" name="pxh" label="排序号" min={0} />
          <ProFormRadio.Group
            label="显示"
            name="display"
            options={[
              { label: '否', value: '0' },
              { label: '是', value: '1' },
            ]}
          />
          <ProFormRadio.Group
            label="状态"
            name="stat"
            options={[
              { label: '活动', value: 'active' },
              { label: '失效', value: 'inactive' },
              { label: '待发布', value: 'suspend' },
            ]}
          />
          <Form.Item
            label="上传图片"
            rules={[
              {
                required: true,
                message: '上传图片必填！',
              },
            ]}
            name="uploadImgs"
          >
            <ImgUpload form={form} fileList={fileList} setFileList={setFileList} maxCount={1} />
          </Form.Item>
          {/*<Form.Item label="选择宽高">
            <Resizable
              ref={divRef}
              onResize={(e, { size }) => {
                setSize(size);
              }}
              style={{ background: '#ccc' }}
              size={size}
              defaultSize={size}
              maxWidth={960}
              maxHeight={600}
              minWidth={100}
              minHeight={100}
            >
              {imgSrc == '' ? null : <img src={imgSrc} style={{ width: '100%', height: '100%' }} />}
            </Resizable>
          </Form.Item>*/}
        </ProForm>
      </Card>
    </PageContainer>
  );
};

export default Index;
